/*
 * Encoder.cpp
 *
 *  Created on: 2012/01/01
 *      Author: nobnak
 */

#include "Encoder.h"

Encoder::Encoder(int samplerate, int brate, int maxNumSamples) {
	lame = lame_init();
	lame_set_in_samplerate(lame, samplerate);
	lame_set_mode(lame, MONO);
	lame_set_num_channels(lame, 1);
	lame_set_brate(lame, brate);
	lame_init_params(lame);

	mp3bufSize = (int) (1.25 * maxNumSamples + 7200);
	mp3buffer = new unsigned char[mp3bufSize];
}

Encoder::~Encoder() {
	lame_close(lame);

	if (mp3buffer != NULL) {
		delete[] mp3buffer;
		mp3buffer = NULL;
	}
}

void Encoder::write(short *data, int n) {
	int write;
	write = lame_encode_buffer(lame, data, NULL, n, mp3buffer, mp3bufSize);
	dst->write(mp3buffer, write);
}
void Encoder::end() {
	int write;
	write = lame_encode_flush(lame, mp3buffer, mp3bufSize);
	dst->write(mp3buffer, write);
	dst->end();
}
void Encoder::pipe(IWritable<unsigned char> *dst) {
	this->dst = dst;
}

